package com.xxx.ssoclient2.redistype;

import lombok.Data;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Data
public class RedisLockDefinitionHolder {
    /**
     * 业务唯一 key
     */
    private String businessKey;
    /**
     * 加锁时间 (秒 s)
     */
    private Long lockTime;
    /**
     * 上次更新时间（ms）
     */
    private Long lastModifyTime;
    /**
     * 保存当前线程
     */
    private Thread currentTread;
    /**
     * 总共尝试次数
     */
    private int tryCount;
    /**
     * 当前尝试次数
     */
    private int currentCount;

    /**
     * 更新的时间周期（毫秒）,公式 = 加锁时间（转成毫秒） / 3
     */
    private Long modifyPeriod;
    public RedisLockDefinitionHolder(String businessKey, Long lockTime, Long lastModifyTime, Thread currentTread, int tryCount) {
        this.businessKey = businessKey;
        this.lockTime = lockTime;
        this.lastModifyTime = lastModifyTime;
        this.currentTread = currentTread;
        this.tryCount = tryCount;
        this.modifyPeriod = lockTime * 1000 / 3;
    }

    /**
     * 线程池，每个 JVM 使用一个线程去维护 keyAliveTime，定时执行 runnable
     */
    private static final ScheduledExecutorService SCHEDULER =
            new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("redisLock-schedule-pool").daemon(true).build());
    static {
        SCHEDULER.scheduleAtFixedRate(() -> {
            // do something to extend time
        }, 0,  2, TimeUnit.SECONDS);
    }
}
